var $$ = Dom7;
var basePath = "http://61.160.250.164:8088/bfmis/";
var app = new Framework7({
	root: '.qrscanner', // App root element
	id: 'io.yachtar.app', // App bundle ID
  	name: 'Yachtar', // App name
	theme: 'auto', // Automatic theme detection
	dialog: {
		// set default title for all dialog shortcuts
		title: '提示',
		// change default "OK" button text
		buttonOk: '确认',
	  }
});

var flag =  sessionStorage.getItem("flag");
var paytype =  sessionStorage.getItem("paytype");

var cordova_app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    onDeviceReady: function() {
        this.receivedEvent('deviceready');
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
		QRScanner.prepare(function(err, status){
			if (err) {
				console.error(err);
			}
			if (status.authorized) {
				//绑定扫描监听
				// `QRScanner.cancelScan()` is called.
				QRScanner.scan(displayContents);
				function displayContents(err, text) {
					if (err) {
						alert('启动扫描出错：' + JSON.stringify(err));
					} else {
						if(flag==1){
							window.location.href = "../../plugin/pay/pay.html";
							sessionStorage.setItem("houseid", text);
						}else if(flag==2){
							var payamount=0.01;
							//var payamount=sessionStorage.getItem("payamount");
							var houseid = sessionStorage.getItem("houseid");
							var userid = sessionStorage.getItem("userid");
							var rate = sessionStorage.getItem("rate");
							var calculatetype = sessionStorage.getItem("calculatetype");
							var params = { paymentcode: text, paytype: paytype,payamount: payamount,houseid: houseid,userid :userid,rate:rate,calculatetype:calculatetype};
							if(paytype == 3) {
								//支付宝
								zfbpay(params);
							}else if(paytype == 4){
								//微信支付
							}
						}
					}
				}
				//开始扫描，需要将页面的背景设置成透明
				QRScanner.show();
			} else if (status.denied) {
				alert('用户拒绝访问摄像头');
			} else {
			}
		  });
        console.log('Received Event: ' + id);
    }
};
cordova_app.initialize();

$$('#back').on('click', function () {
	if(flag==2){
		window.location.href = "../../plugin/pay/pay.html";
	}else{
		window.location.href = "../../plugin/homepage/homepage.html";
	}
});	

function zfbpay(params){
	$.ajax({
		type: "POST",
		url: basePath + "pay/zfbpay.yachtar",
		//url: "http://192.168.0.106:8080/bfmis/pay/zfbpay.yachtar",
		data: JSON.stringify(params),
		dataType: "json",
		contentType: "application/json;charset=UTF-8",
		success: function (data) {
			if (data.result=="SUCCESS") {
				window.location.href = "../../plugin/pay/paysuc.html";
			} else if(data.result=="FAILED"){
				app.dialog.alert("支付宝支付失败!");
			} else if(data.result=="UNKNOWN"){
				app.dialog.alert("系统异常，订单状态未知!");
			} else {
				app.dialog.alert("不支持的交易状态，交易返回异常!");
			} 
		}
	});
}